﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;

namespace uzing
{
    public class uzCTcpListenerAsync
    {
        TcpListener listener;
        EndCallback endCallback;
        public delegate void EndCallback(object parameter);

        public int Open(int Port)
        {
            listener = new TcpListener(IPAddress.Any, Port);
            var endPoint = (IPEndPoint)listener.LocalEndpoint;
            var retVal = endPoint.Port;
            listener.Start();
            return retVal;
        }

        public void BeginAcceptTcpClient(EndCallback asyncEndCallback)
        {
            listener.BeginAcceptTcpClient(_endCallback, listener);
            endCallback = asyncEndCallback;
        }

        private void _endCallback(IAsyncResult result)
        {
            TcpClient client = listener.EndAcceptTcpClient(result);
            var uzClient = new uzCTcpClientAsync();
            uzClient.RegisterClient(client);
            endCallback(uzClient);
        }
    }
}
